package com.example.ordersystem.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ordersystem.common.Result;
import com.example.ordersystem.entity.Product;
import com.example.ordersystem.service.ProductService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/product")
@CrossOrigin
public class ProductController {

    @Resource
    private ProductService productService;

    @GetMapping("/page")
    public Result<Page<Product>> page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String name) {
        Page<Product> productPage = productService.page(pageNum, pageSize, name);
        if (productPage.getRecords().isEmpty() && name != null && !name.isEmpty()) {
            return Result.error("暂无此商品");
        }
        return Result.success(productPage);
    }

    @PostMapping
    public Result<String> save(@RequestBody Product product) {
        if (productService.existsByName(product.getName())) {
            return Result.error("商品已存在");
        }
        productService.save(product);
        return Result.success("商品添加成功");
    }

    @PutMapping
    public Result<String> update(@RequestBody Product product) {
        Product existingProduct = productService.getById(product.getProductId());
        if (existingProduct == null) {
            return Result.error("无此商品，无法修改");
        }
        // 检查新名称是否与其他商品重复（排除自身）
        if (!existingProduct.getName().equals(product.getName()) &&
                productService.existsByName(product.getName())) {
            return Result.error("商品名称已存在");
        }
        productService.update(product);
        return Result.success("商品修改成功");
    }

    @DeleteMapping("/{id}")
    public Result<String> remove(@PathVariable Integer id) {
        Product product = productService.getById(id);
        if (product == null) {
            return Result.error("商品不存在");
        }
        productService.removeById(id);
        return Result.success("商品删除成功");
    }

    @GetMapping("/{id}")
    public Result<Product> getById(@PathVariable Integer id) {
        Product product = productService.getById(id);
        if (product == null) {
            return Result.error("商品不存在");
        }
        return Result.success(product);
    }

    @DeleteMapping("/name/{name}")
    public Result<String> removeByName(@PathVariable String name) {
        if (!productService.existsByName(name)) {
            return Result.error("商品不存在");
        }
        productService.removeByName(name);
        return Result.success("商品删除成功");
    }

    @GetMapping("/exists/{name}")
    public Result<Boolean> existsByName(@PathVariable String name) {
        return Result.success(productService.existsByName(name));
    }
}